/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include "Simple.h"
#include <xml/Object.h>
#include <xml/Stream.h>
#include <resource/Manager.h>
#include <libfunc.h>
#include <textstream/File.h>
#include <xml/Saver.h>

#include <boost/scoped_ptr.hpp>

namespace liba {
namespace lib3d {
namespace selector {

class Loader: public xml::ObjectANSI
{
public:
	Loader( hard::Hardware * hardware ):
		hardware(hardware)
	{}

	bool on_attribute( xml::Provider * prov, const std::string & name, const std::string & value )
	{
		if( name == "Adapter")
		{
			lib3d::hard::Manager::HardwareList items = lib3d::hard::Manager::get_hardwares();
			lib3d::hard::Manager::HardwareList::const_iterator i = std::find_if(items.begin(), items.end(), compare_name_ptr<std::string>( value ) );
			if( i != items.end() )
			{
				hardware = *i;
				return true;
			}
		}
		if( !hardware )return false;
		return hardware->set_attribute( name, value );
	}

	virtual void on_save_attributes( xml::SaverBase * saver )const
	{
		if(!hardware)return;
		saver->save_attribute( "Adapter", hardware->get_name() );
		lib3d::hard::Strings items = hardware->GetAttribute_names();
		for( lib3d::hard::Strings::const_iterator i = items.begin(); i != items.end(); ++i )
		{
			saver->save_attribute( *i , hardware->GetAttribute( *i ) );
		}
	}
	
	hard::Hardware * hardware;
};

Simple::Simple()	
{}

Simple::~Simple()
{}

hard::Hardware * Simple::set_mode( WindowImpl * wnd )
{
	hard::Manager::HardwareList::const_iterator it = hard::Manager::get_hardwares().begin();
	for( ; it != hard::Manager::get_hardwares().end(); ++it )
	{
		hard::Hardware * hardware = (*it);
		if( hardware->set_mode( wnd ) )
			return hardware;
	}
	return 0;
}

void Simple::change_mode( WindowImpl * wnd )
{}

hard::Hardware * Simple::load( const filesystem::String & config_filename )
{
	Loader loader(0);
	boost::scoped_ptr<resource::Resource> res(resource::Manager::create_resource( config_filename ));
	if( !xml::StreamResource(res.get()).load( &xml::Root( &loader, "VideoSettings" ) ) )
		return 0;
	return loader.hardware;
}

bool Simple::save( hard::Hardware * hardware, const filesystem::String & config_filename )const
{
	textstream::File<char> ts( config_filename );
	return xml::SaverText<char>( &ts ).save_node( "VideoSettings", &Loader(hardware) );
}

} // namespace selector
} // namespace lib3d
} // namespace liba

